package org.osprey.apidoc.auth;

import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.PubSecKeyOptions;
import io.vertx.ext.auth.User;
import io.vertx.ext.auth.jwt.JWTAuth;
import io.vertx.ext.auth.jwt.JWTAuthOptions;
import io.vertx.ext.jwt.JWTOptions;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @ClassName JwtProvider
 * @Description:
 * @Author Osprey
 * @Date 2019/10/21
 * @Version V2.0
 **/
public class JwtProvider {
    private static JWTAuthOptions config = new JWTAuthOptions().addPubSecKey(new PubSecKeyOptions().setSymmetric(true).setAlgorithm("HS256")
            .setPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzizZZdhKzOdARSlWhF9o74jc06akHGM7pTTcagOU9QG4oqE0AM6Q4vnK5KVEh9sy12tcqv8kTyVuxpYO1oURj8zR4EcVp8x/5r9xWFFNyBh7BnwiSSNQQYrZo0ph/Zxtf3Rby41+Zr74Y8H0rQLdD5MOXYSpJD8XFdnk/zRdY7XHLqbt2ayzn5cbCmcmSb6WPVNOsZ7Y1jHCMG3q7lOnlGr+6b7G3HbxYRUyezJ5YlDHcijzJ4fj+UM2H6qzYsyqPP1Qv0+f9lPzSVdA01F9ct2DOUi+jNwWn+HXv62GwqqInMrL/Z+/ipmadTB3/JohenPKNIrXGEEoLnfBzKFS1wIDAQAB")
            .setSecretKey("MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDOLNll2ErM50BFKVaEX2jviNzTpqQcYzulNNxqA5T1AbiioTQAzpDi+crkpUSH2zLXa1yq/yRPJW7Glg7WhRGPzNHgRxWnzH/mv3FYUU3IGHsGfCJJI1BBitmjSmH9nG1/dFvLjX5mvvhjwfStAt0Pkw5dhKkkPxcV2eT/NF1jtccupu3ZrLOflxsKZyZJvpY9U06xntjWMcIwberuU6eUav7pvsbcdvFhFTJ7MnliUMdyKPMnh+P5QzYfqrNizKo8/VC/T5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2i1XYa3JmYrHaCAmWfB9JmJDmdgvRP8OE1YQ7nSxc6YsZabJNbEqnvKPDAoGBAKSCXlsb8iXMbGcwEkwLeJ866onoYGg78mB+eukFVlgqYKhP6Zhfm7HHDIniXwAHvWO3/tCnfBtvPoH/afchjZ2CGEO91RdH27ro6m/e38BW+Vm7JhqLyv6c+ldE24yyIWi9avqL6zl75fJ19Xr/5ljPjOx/3uGncfJLjgo51s1W"));

    /**
     * JWT 签名生成
     *
     * @return
     */
    public static String generateToken(Vertx vertx, JsonObject jsonObject) {
        return JWTAuth.create(vertx, config).generateToken(jsonObject, new JWTOptions().setAlgorithm("HS256"));
    }

    /**
     * Token解析
     * @param token
     */
    public static JsonObject authenticate(Vertx vertx, String token) {
        AtomicReference<JsonObject> data = null;
        JWTAuth.create(vertx, config).authenticate(new JsonObject().put("jwt", token), res -> {
            if (res.succeeded()) {
                User user = res.result();
                data.set(user.principal());
            }
        });
        return JsonObject.mapFrom(data);
    }
}
